import {
  getPSYList,
  getFJYList,
  getJsdList,
  getPickUpStore,
  getSettlement,
  createOrder
} from '../../api/cart.js'
import Message from 'tdesign-miniprogram/message/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabIndex: 0,
    tabList: [{
        label: '骑士配送'
      },
      {
        label: '到店自提'
      }
    ],
    personIndex: 0,
    cartList: [],
    remark: '',
    allTotalPrice: 0,
    addressInfo: null,
    personList: [],
    psyInfo: [], // 配送员集合
    fjyInfo: [], // 分拣员集合
    jsdList: [], // 即时达集合
    jsdObj: null,
    popupVisible: false,
    areaRadioIndex: -1,
    ztdList: [], // 自提点集合
    payInfo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // const {
    //   allTotalPrice,
    //   cartList
    // } = wx.getStorageSync('cartData')
    // this.setData({
    //   allTotalPrice,
    //   cartList
    // }, () => {
    //   // wx.removeStorage({key: 'cartData'})
    // })

    this.init()
  },
  async init() {
    const psyInfo = await getPSYList()
    const fjyInfo = await getFJYList()
    const jsdList = await getJsdList()
    const ztdList = await getPickUpStore()
    const cartItems = wx.getStorageSync('cartItems') || []
    const params = {
      items: [].concat(cartItems),
      pointStatus: true
    }
    const res = await getSettlement(params)
    let price = res.price
    price.totalPrice = (price.totalPrice / 100).toFixed(2)
    price.deliveryPrice = (price.deliveryPrice / 100).toFixed(2)
    price.payPrice = (price.payPrice / 100).toFixed(2)
    res.shopItems.map(yy=> {
      yy.items.map(hh=>{
        hh.totalPrice = (hh.price / 100 * hh.count).toFixed(2)
        hh.price = (hh.price / 100).toFixed(2)
      })
    }) 

    const address = !!wx.getStorageSync('address') ? wx.getStorageSync('address') : res.address
    this.setData({
      addressInfo: address,
      psyInfo,
      fjyInfo,
      personList: [...psyInfo],
      jsdList,
      jsdObj: jsdList[0],
      ztdList,
      payInfo: res,
      cartList: res.shopItems
    }, () => {
      wx.removeStorage({
        key: 'cartItems'
      })
      wx.removeStorage({
        key: 'address'
      })
    })
  },
  onTabsChange(e) {
    this.setData({
      tabIndex: e.detail.value,
      personList: e.detail.value === 0 ? [...this.data.psyInfo] : [...this.data.fjyInfo]
    })
  },
  tabClick(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setData({
      personIndex: index
    })
  },
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },
  areaRadioChange(e) {
    this.setData({
      areaRadioIndex: e.detail.value
    })
  },
  selectAddress() {
    wx.navigateTo({
      url: '/pages/usercenter/address/list/index?selectMode=true'
    })
  },
  async nowPay() {
    let arr = this.data.cartList.map(yy => {
      let obj = {}
      yy.items.map(uu => {
        obj.cartId = uu.cartId
        obj.skuId = uu.skuId
        obj.count = uu.count
      })

      return obj
    })
    const data = this.data
    let params = {
      items: arr,
      pointStatus: false,
      remark: data.remark,
      couponId: '', // 优惠券id
      deliveryType: data.tabIndex === 0 ? '3' : '2', // 配送方式(用户自提2，骑士配送3)                    
      receiverName: data.addressInfo.name, // 收件人名称
      receiverMobile: data.addressInfo.mobile, // 收件人手机
      deliveryTimeValue: data.jsdObj.value, // 配送时间
      seckillActivityId: '', // 秒杀活动编号
      combinationActivityId: '', // 拼团活动编号
      combinationHeadId: '', // 拼团团长编号
      bargainRecordId: '', // 砍价记录编号
      pointActivityId: '' // 积分商城活动编号      
    }

    if (params.deliveryType === '3') {
      if (!data.addressInfo) {
        return Message.info({
          context: this,
          offset: [90, 32],
          duration: 2000,
          icon: false,
          // single: false, // 打开注释体验多个消息叠加效果
          content: '请选择收货地址！',
        })
      }
      params.deliveryUserId = data.personList[data.personIndex].id // 配送员编号
      params.addressId = data.addressInfo.id // 收件地址编号
    } else {
      if (data.areaRadioIndex === -1) {
        return Message.info({
          context: this,
          offset: [90, 32],
          duration: 2000,
          icon: false,
          // single: false, // 打开注释体验多个消息叠加效果
          content: '请选择自提点！',
        })
      }
      params.sortUserId = data.personList[data.personIndex].id // 分拣员编号    
      params.pickUpStoreId = data.ztdList[data.areaRadioIndex].id // 自提门店编号
    }
    const res = await createOrder(params)
    if (res) {
      wx.navigateTo({
        url: `/pages/cashRegister/index?id=${res.id}&payOrderId=${res.payOrderId}&payPrice=${this.data.payInfo.price.payPrice}`
      })
    }
  },
  remarkChange(e) {
    this.setData({
      remark: e.detail.value
    })
  },
  showTimeSelect() {
    this.setData({
      popupVisible: true
    })
  },
  selectTime(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setData({
      jsdObj: this.data.jsdList[index],
      popupVisible: false
    })
  }
})